package com.backstage.common.uitil;

import com.backstage.common.base.bean.Message;
import com.backstage.common.base.enum_bean.MessageEnumStatus;
import com.backstage.common.base.enum_bean.MessageEnumTitle;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * hibernate-validator校验工具类
 * 参考文档：http://docs.jboss.org/hibernate/validator/5.4/reference/en-US/html_single/
 */
public class ValidatorUtils {
    private static Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 校验实体类
     * @param bean 校验对象
     * @param groups 校验组
     * @return Message
     */
    public static <Q> Message validateEntity(Q bean, Class<?>... groups) {
        Set<ConstraintViolation<Q>> constraintViolations = validator.validate(bean, groups);
        if (!constraintViolations.isEmpty()) {
        	ConstraintViolation<Q> constraint = (ConstraintViolation<Q>)constraintViolations.iterator().next();
        	return new Message(MessageEnumStatus.FAIL, MessageEnumTitle.失败, constraint.getMessage());
        }else{
            return Message.VALIDATE_SUCCESS;
        }

    }
}
